<template>
  <CustomModal
    :title="props.type === 'add' ? '添加步骤' : '步骤修改'"
    v-model="visible"
    isTitle
    :isTabbar="false"
    :disabledCancelButtonClose="true"
    :showCancelButton="props.type === 'add' ? false : true"
    cancelText="更新"
    :confirmText="props.type === 'add' ? '确定' : '删除'"
    @cancel="handleUpdateStep"
    @confirm="handleConfirmStep"
  >
    <scroll-view class="scroll-content" scroll-y>
      <uni-forms
        ref="uFormRef"
        label-position="left"
        :modelValue="formData"
        :rules="rules"
        class="nw-forms"
      >
        <uni-forms-item name="ingredientType">
          <template #label>
            <view class="nw-label">选择类别:</view>
          </template>
          <view class="nw-select-category">
            <view class="nw-select-wrap" @click="handleSelectCategory">
              <view
                :class="[
                  'input-text',
                  formData.ingredientType ? '' : 'input-placeholder'
                ]"
              >
                {{ formData.ingredientType ? categoryName : '选择' }}
              </view>
              <nw-Icons :type="actionSheetShow ? 'up' : 'down'" />
            </view>
          </view>
        </uni-forms-item>
        <view class="ul">
          <uni-forms-item
            v-if="formData.ingredientType === 'material'"
            :required="false"
            style="flex-direction: column"
          >
            <template #label>
              <view class="li-title">
                <view class="li-label">食材盒{{ boxIndex }}:</view>
                <view class="li-right">
                  <nw-Button
                    class="active"
                    icon="plus"
                    text="添加食材"
                    @click="handleAddIngredient"
                  ></nw-Button>
                </view>
              </view>
            </template>
            <view class="nw-table nw-table2">
              <view class="tr">
                <view class="th">食材名称</view>
                <view class="th">用量(克/g)</view>
                <view class="th">加工方式</view>
                <view class="th">操作</view>
              </view>
              <view class="tbody">
                <view class="tr" v-for="(row, i) in materialList" :key="row">
                  <view class="td">
                    <nw-PickerSelect
                      v-model="actionSheetValue"
                      :columns="[ingredientOptions]"
                      :text="
                        g_options.getOptionText(
                          allIngredientOptions,
                          row.target
                        )
                      "
                      @select="handleSelect(1, row, i)"
                      @change="handleActionSelectChange"
                      @confirm="handleActionSelectConfirm"
                    />
                  </view>
                  <view class="td">
                    <nw-Input
                      v-model.number="row.goal"
                      placeholder="用量"
                      type="number"
                      verifyType="nzint"
                      :maxlength="10"
                    ></nw-Input>
                  </view>
                  <view class="td">
                    <nw-PickerSelect
                      v-model="actionSheetValue"
                      :columns="[materialProcessDropList]"
                      :text="
                        g_options.getOptionText(
                          materialProcessDropList,
                          row.processId
                        )
                      "
                      @select="handleSelect(2, row, i)"
                      @change="handleActionSelectChange"
                      @confirm="handleActionSelectConfirm"
                    />
                  </view>
                  <view class="td">
                    <nw-Button
                      text="删除"
                      @click="handleDeleteIngredient(row, i)"
                    ></nw-Button>
                  </view>
                </view>
                <view v-if="!materialList.length" class="empty-list">
                  当前为空食材
                </view>
              </view>
            </view>
          </uni-forms-item>
          <uni-forms-item name="timeOffset">
            <template #label>
              <view class="li-label">步骤时长:</view>
            </template>
            <nw-Input
              v-model.number="formData.timeOffset"
              label="步骤时长"
              type="number"
              verifyType="nzint"
              :maxlength="10"
            >
              <template #right>
                <view class="unit">秒/s</view>
              </template>
            </nw-Input>
          </uni-forms-item>
          <uni-forms-item
            v-if="formData.ingredientType === 'flavour'"
            name="goal"
          >
            <template #label>
              <view class="li-label">重量:</view>
            </template>
            <nw-Input
              v-model.number="formData.goal"
              label="重量"
              type="number"
              verifyType="nzint"
              :maxlength="10"
            >
              <template #right>
                <view class="unit">克/g</view>
              </template>
            </nw-Input>
          </uni-forms-item>
          <uni-forms-item
            v-if="formData.ingredientType === 'material'"
            name="turnCount"
          >
            <template #label>
              <view class="li-label">翻倒次数:</view>
            </template>
            <nw-Input
              v-model.number="formData.turnCount"
              label="翻倒次数"
              type="number"
              verifyType="nzint"
              :maxlength="1"
            ></nw-Input>
          </uni-forms-item>
        </view>
      </uni-forms>
    </scroll-view>
  </CustomModal>

  <nw-ActionSheet
    v-if="actionSheetShow"
    ref="uwActionSheetRef"
    v-model:show="actionSheetShow"
    v-model="actionSheetValue"
    :columns="actionSheetColumns"
    @change="handleActionSelectChange"
    @confirm="handleActionSelectConfirm"
  />
  <IngredientBoxTip
    v-if="ingredientBoxTipVisible"
    v-model="ingredientBoxTipVisible"
  />
  <DeleteIngredient
    v-if="deleteIngredientVisible"
    v-model="deleteIngredientVisible"
    :row="rowData"
    @confirm="handleDeleteIngredientConfirm"
  />
</template>

<script setup>
import IngredientBoxTip from './IngredientBoxTip.vue'
import DeleteIngredient from './DeleteIngredient.vue'

defineOptions({
  name: 'AddOrEditStep',
  inheritAttrs: false
})

const props = defineProps({
  type: {
    type: String,
    default: '' // add-新增步骤 edit-编辑步骤
  },
  row: {
    type: Object,
    default: () => {}
  },
  boxIndex: {
    type: [String, Number],
    default: ''
  },
  stepList: {
    type: Array,
    default: () => []
  }
})
const visible = defineModel({
  type: Boolean,
  default: false
})
const emit = defineEmits(['confirm', 'update', 'delete'])

const recipeStore = useRecipeStore()
const { recipeCategoryList, materialProcessDropList } = storeToRefs(recipeStore)
const uFormRef = ref(null)
const formData = ref({
  name: '',
  ingredientType: '',
  ingredientName: '',
  target: '',
  targetId: '',
  goal: '',
  turnCount: 1,
  timeOffset: ''
})
// 校验规则
const rules = {
  ingredientType: {
    rules: g_rules.selectRule('类别')
  },
  get goal() {
    return {
      rules: g_rules.stepGoal(
        formData.value.ingredientType === 'material' ? '食材重量' : '调料重量'
      )
    }
  },
  turnCount: {
    rules: g_rules.turnCount
  },
  timeOffset: {
    rules: g_rules.commonInputText('步骤时长')
  }
}
const stepCategoryList = ref([])
const categoryName = ref('')
const materialList = ref([])
// 弹框参数
const uwActionSheetRef = ref(null)
const actionSheetShow = ref(false)
const actionSheetValue = ref([])
const actionSheetColumns = ref([])
const ingredientBoxTipVisible = ref(false)
const deleteIngredientVisible = ref(false)
const rowData = ref({})
const ingredientType = ref('')
const ingredientIndex = ref('')
// 初始化展示所有食材列表
const allIngredientOptions = ref(
  g_.cloneDeep(recipeCategoryList.value).find(item => item.value === 'material')
    ?.ingredientList || []
)
const ingredientOptions = ref()

onMounted(_ => {
  if (props.type === 'edit' && props.row) {
    g_utils.assignFormData(formData.value, props.row)
    materialList.value = props.row.materialList || []
    console.log('props.row', props.row)
    console.log('formData.value', formData.value)
  }
  getConfig()
  getDictDropList()
})

const getConfig = _ => {
  getStepCategoryList()
  dealConfigData()
  recipeStore
    .setRecipeCategoryList()
    .then(({ code, data }) => {
      if (code === 200 && data) {
        getStepCategoryList()
      }
    })
    .finally(_ => {
      dealConfigData()
    })
}

const getDictDropList = _ => {
  recipeStore.setMaterialProcessDropList()
}

const getStepCategoryList = _ => {
  // 处理步骤分类列表，如果是食材类别则清空食材列表
  stepCategoryList.value = g_
    .cloneDeep(recipeCategoryList.value)
    .filter(item => {
      if (
        props.type === 'add' &&
        props.boxIndex > 4 &&
        item.value === 'material'
      ) {
        return false
      } else {
        if (item.value === 'material') item.ingredientList = []
        return true
      }
    })
  console.log('stepCategoryList.value', stepCategoryList.value)
}

const dealConfigData = _ => {
  const data = stepCategoryList.value
  const [valueArr, labelArr] = g_busTool.findAllValues(
    data,
    formData.value.ingredientType === 'material'
      ? formData.value.ingredientType
      : formData.value.target
  )
  actionSheetValue.value = valueArr
  categoryName.value = labelArr.join('/')
  setSheetColumns()
  console.log('actionSheetValue.value', actionSheetValue.value)
}

const setSheetColumns = _ => {
  actionSheetColumns.value = []
  if (actionSheetValue.value.length) {
    // 获取当前下拉选择器列表
    let currentList = stepCategoryList.value
    for (const value of actionSheetValue.value) {
      const foundItem = currentList?.find(item => item.value === value)
      if (foundItem) {
        actionSheetColumns.value.push(currentList)
        currentList = foundItem.ingredientList
      } else {
        actionSheetColumns.value.push([])
      }
    }
  } else {
    // 无查询值时：获取默认的三层结构
    const firstLevel = stepCategoryList.value
    const secondLevel = firstLevel[0]?.ingredientList || []
    const thirdLevel = secondLevel[0]?.ingredientList || []
    actionSheetColumns.value.push(firstLevel, secondLevel, thirdLevel)
  }
  if (actionSheetColumns.value.length < 3) {
    actionSheetColumns.value.push([])
  }
  console.log('actionSheetColumns.value', actionSheetColumns.value)
}

const handleSelectCategory = _ => {
  // 赋值类别的值
  actionSheetValue.value = formData.value.ingredientType
    ? [formData.value.ingredientType, formData.value.target]
    : []
  console.log('handleSelectCategory:', actionSheetValue.value, formData.value)
  setSheetColumns()
  ingredientType.value = 3
  actionSheetShow.value = true
}

const handleSelect = (type, row, i) => {
  console.log('handleSelect:', type, row, i)
  if (type === 1) {
    getIngredientOptions(row.target)
    actionSheetValue.value = [row.target]
  } else {
    actionSheetValue.value = [row.processId]
  }
  ingredientType.value = type
  ingredientIndex.value = i
  // row.show = true
  // actionSheetShow.value = true
}

const getIngredientOptions = target => {
  // 获取已有食材列表（去重）
  const ingredientList = []
  props.stepList.forEach(item => {
    if (item.ingredientType === 'material') {
      item.materialList.forEach(material => {
        material.target !== target && ingredientList.push(material.target + '')
      })
    }
  })
  // 过滤可用食材选项（排除已使用的食材）
  ingredientOptions.value =
    g_
      .cloneDeep(recipeCategoryList.value)
      .find(item => item.value === 'material')
      ?.ingredientList?.filter(item => !ingredientList.includes(item.value)) ||
    []
  console.log('ingredientOptions.value', ingredientOptions.value)
}

const handleActionSelectChange = e => {
  console.log('handleActionSelectChange', e)
  const { columnIndex, value, values, index, indexs } = e
  if (index === undefined || index === null) return
  if (ingredientType.value !== 3) return

  if (columnIndex === 0) {
    uwActionSheetRef.value.ref.setColumnValues(
      1,
      stepCategoryList.value[index].ingredientList
    )
    uwActionSheetRef.value.ref.setColumnValues(
      2,
      stepCategoryList.value[index]?.ingredientList[0]?.ingredientList || []
    )
  } else if (columnIndex === 1) {
    uwActionSheetRef.value.ref.setColumnValues(
      2,
      stepCategoryList.value[indexs[0]]?.ingredientList[index]
        ?.ingredientList || []
    )
  }
}

const handleActionSelectConfirm = e => {
  console.log('handleActionSelectConfirm', e, actionSheetValue.value)
  const data = e.value.filter(i => i)
  const checkedNode = data[data.length - 1]
  if (ingredientType.value === 1) {
    materialList.value[ingredientIndex.value] = {
      ...materialList.value[ingredientIndex.value],
      show: false,
      ingredientName: checkedNode.label,
      target: checkedNode.value
    }
  } else if (ingredientType.value === 2) {
    materialList.value[ingredientIndex.value] = {
      ...materialList.value[ingredientIndex.value],
      show: false,
      processId: checkedNode.value
    }
  } else {
    formData.value.ingredientType = data?.length ? data[0].value : ''
    formData.value.ingredientName = checkedNode?.label || ''
    formData.value.target = checkedNode?.value || ''
    formData.value.targetId = g_busTool.getRecipeTargetId(formData.value)
    categoryName.value = data.map(item => item.label).join('/')
    // 设置初始值
    formData.value.turnCount = ''
    formData.value.goal = g_busTool.getRecipeGoal(formData.value)
    if (formData.value.ingredientType === 'material') {
      formData.value.turnCount = 1
      // 默认添加一个食材
      materialList.value.push({
        show: false,
        ingredientName: '',
        target: '',
        goal: '',
        processId: ''
      })
    }
    // 清除重量的提示
    uFormRef.value.clearValidate(['goal'])
  }
}

const handleAddIngredient = _ => {
  console.log('handleAddIngredient')
  // 不能超过8种食材
  if (materialList.value.length >= 8) return
  materialList.value.push({
    show: false,
    ingredientName: '',
    target: '',
    goal: '',
    processId: ''
  })
}

const handleRoleChange = (e, row, i) => {
  // console.log('handleRoleChange', e, row, i)
}

const handleDeleteIngredient = (row, i) => {
  console.log('handleDeleteIngredient', row, i)
  rowData.value = row
  ingredientIndex.value = i
  deleteIngredientVisible.value = true
}

const handleDeleteIngredientConfirm = _ => {
  console.log('handleDeleteIngredientConfirm')
  materialList.value.splice(ingredientIndex.value, 1)
}

// 获取表单提交的数据
const getFormData = _ => {
  const formDataCopy = {
    ...formData.value
  }
  if (formDataCopy.ingredientType === 'material') {
    const ingredientData = materialList.value[0]
    formDataCopy.ingredientName = ingredientData.ingredientName
    formDataCopy.goal = ingredientData.goal
    formDataCopy.target = ingredientData.target
  }
  materialList.value = materialList.value.map(item => {
    // 删除多余字段
    delete item.show
    return item
  })

  return {
    ...formDataCopy,
    name: g_busTool.getRecipeStepName({
      ...formDataCopy,
      materialList: materialList.value
    }),
    materialList: materialList.value
  }
}

const handleUpdateStep = _ => {
  console.log('handleUpdateStep')
  uFormRef.value
    .validate()
    .then(res => {
      console.log('handleUpdateStep-success', formData.value)
      emit('update', getFormData())
      visible.value = false
    })
    .catch(err => {
      console.log('err', err)
    })
}

const handleConfirmStep = _ => {
  console.log('handleConfirmStep Or handleDeleteStep', formData.value)
  // 校验食材数据不能为空
  if (formData.value.ingredientType === 'material') {
    const found = materialList.value.find(item => {
      return Object.values(item).includes('')
    })
    if (!materialList.value.length || found) {
      ingredientBoxTipVisible.value = true
      return
    }
  }
  if (props.type === 'add') {
    uFormRef.value
      .validate()
      .then(res => {
        console.log('formData.value-confirm', formData.value)
        emit('confirm', getFormData())
        visible.value = false
      })
      .catch(err => {
        console.log('err', err)
      })
  } else {
    emit('delete', formData.value)
    visible.value = false
  }
}
</script>

<style lang="scss" scoped>
@import './../scss/AddOrEditStep.scss';
</style>
